import React, {useState} from "react";
import {Button, Grid} from "@material-ui/core";
import {AddRounded, CloudDownloadRounded} from "@material-ui/icons";

import {EnhancedTable, Toolbar} from "../../shared/components"
import {getFaults} from "../../shared/services/data.service";

const ViewAllFault = ({onAdd, onRowClick, ...props}) => {
    const [faultList, setFaultList] = useState([]);

    const getFaultList = () => (
        new Promise((resolve, reject) => {
            getFaults().then(res => {
                const newFaultList = res.data.map(fault => ({
                    id: fault.id,
                    name: fault.name,
                    type: fault.fault_type,
                    vehicle: fault.vehicle.name,
                    status: fault.vehicle.status
                }))
                setFaultList(newFaultList);
                resolve(newFaultList);
            }).catch(error => reject(error));
        })
    );

    return (
        <Grid container spacing={4}>
            <Toolbar
                title="Fault List"
                actions={<React.Fragment>
                    <Button
                        variant="contained"
                        color="primary"
                        startIcon={<AddRounded/>}
                        onClick={onAdd}
                    >
                        Add Fault
                    </Button>
                </React.Fragment>}
            />

            <Grid item xs={12}>
                <EnhancedTable
                    title={"Fault List"}
                    schema={[
                        {id: 'id', label: 'Id', hidden: true},
                        {id: 'vehicle', label: 'Vehicle', sort: true},
                        {id: 'name', label: 'Fault', sort: true},
                        {id: 'status', label: 'Status', sort: true},
                        {id: 'fault_type', label: 'Type', sort: true},
                        // {id: 'source', label: 'Source', sort: true},
                        // {id: 'workOrder', label: 'Work Order', sort: true}
                    ]}
                    async={{loading: true, loadingData: getFaultList}}
                    pagination={faultList.length > 5}
                    actions={[
                        {id: "downloadExcel", tooltip: "Download Excel", icon: CloudDownloadRounded}
                    ]}
                    onRowClick={onRowClick}
                />
            </Grid>
        </Grid>
    );
};

export default ViewAllFault;
